package com.test.qnews.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.test.qnews.MainActivity;
import com.test.qnews.R;
import com.test.qnews.clicklistener.OnChangedListener;
import com.test.qnews.custom.DayNightMode;
import com.test.qnews.custom.SlipButton;
import java.io.File;
import java.math.BigDecimal;



/**
 * Created by dllo on 16/1/9.
 */
public class SetActivity extends BaseActivity implements View.OnClickListener,OnChangedListener {

    private SlipButton mSlipButton;
    private TextView cleanTv;
    private Handler handler;

    private DataCleanManager dataCleanManager = new DataCleanManager();
    @Override
    protected int setLayout() {
        return R.layout.activity_set;
    }

    @Override
    protected void initView() {
        findViewById(R.id.btn_sun_night).setOnClickListener(this);
        findViewById(R.id.btn_clean).setOnClickListener(this);
        cleanTv = (TextView) findViewById(R.id.tv_clean);
        try {
            cleanTv.setText(dataCleanManager.getTotalCacheSize(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        mSlipButton = (SlipButton) this.findViewById(R.id.on);
        mSlipButton.SetOnChangedListener(this);//设置事件监听

    }

    @Override
    public void onClick(View v) {
        int theme = DayNightMode.getDayNightMode(this);
        switch (v.getId()){
            case R.id.btn_sun_night:
                MainActivity.mainActivity.finish();
                if (theme == DayNightMode.THEME_SUN){
                    DayNightMode.setDayNightMode(this, DayNightMode.THEME_NIGHT);
                }else {
                    DayNightMode.setDayNightMode(this, DayNightMode.THEME_SUN);
                }
                // 注意改过主题后一定要，把activity finish在重开一遍，
                // 因为更改主题只能在oncreat中进行
//                this.finish();
                this.startActivity(new Intent(this, MainActivity.class));
                finish();
                break;
            case R.id.btn_clean:
                dataCleanManager.clearAllCache(this);
                handler = new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        cleanTv.setText("0K");
                        return false;
                    }
                });
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(500);
                            handler.sendEmptyMessage(0);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
        }
    }
    public void OnChanged(boolean CheckState) {
        if (CheckState) {
            Toast.makeText(this, "打开了", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "关闭了", Toast.LENGTH_LONG).show();
        }
    }







    /********************************************************************
     * 清理缓存
     */

    public class DataCleanManager {

        public  String getTotalCacheSize(Context context) throws Exception {
            long cacheSize = getFolderSize(context.getCacheDir());
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                cacheSize += getFolderSize(context.getExternalCacheDir());
            }
            return getFormatSize(cacheSize);
        }


        public  void clearAllCache(Context context) {
            deleteDir(context.getCacheDir());
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                deleteDir(context.getExternalCacheDir());
            }
        }

        private  boolean deleteDir(File dir) {
            if (dir != null && dir.isDirectory()) {
                String[] children = dir.list();
                for (int i = 0; i < children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
            return dir.delete();
        }

        // 获取文件
        //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
        //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
        public  long getFolderSize(File file) throws Exception {
            long size = 0;
            try {
                File[] fileList = file.listFiles();
                for (int i = 0; i < fileList.length; i++) {
                    // 如果下面还有文件
                    if (fileList[i].isDirectory()) {
                        size = size + getFolderSize(fileList[i]);
                    } else {
                        size = size + fileList[i].length();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return size;
        }

        /**
         * 格式化单位
         *
         * @param size
         * @return
         */
        public  String getFormatSize(double size) {
            double kiloByte = size / 1024;
            if (kiloByte < 1) {
//            return size + "Byte";
                return "0 KB";
            }

            double megaByte = kiloByte / 1024;
            if (megaByte < 1) {
                BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
                return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                        .toPlainString() + " KB";
            }

            double gigaByte = megaByte / 1024;
            if (gigaByte < 1) {
                BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
                return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                        .toPlainString() + " MB";
            }

            double teraBytes = gigaByte / 1024;
            if (teraBytes < 1) {
                BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
                return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                        .toPlainString() + " GB";
            }
            BigDecimal result4 = new BigDecimal(teraBytes);
            return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                    + " TB";
        }

    }

}
